package com.ibeeking.found.uaa.c.config.auth.sms;

import com.ibeeking.found.uaa.c.config.auth.token.AbstractCustomTokenGranter;
import com.ibeeking.found.uaa.c.model.ClientUserDetails;
import com.ibeeking.found.uaa.c.model.WxSmsCodeModel;
import com.ibeeking.found.uaa.c.service.IClientUserDetailsService;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

/**
 * @Author ibeeking
 */
public class WxSmsCodeTokenGranter extends AbstractCustomTokenGranter {

    private static final String GRANT_TYPE = "sms_code";
    private static final String OPEN_PARAM = "open_id";
    private static final String PHONE_PARAM = "mobile";
    private static final String CODE_PARAM = "code";
    private static final String KEY_PARAM = "key";

    private final IClientUserDetailsService userDetailsServiceImpl;

    public WxSmsCodeTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsServiceImpl, OAuth2RequestFactory requestFactory, IClientUserDetailsService userDetailsServiceImpl) {
        super(tokenServices, clientDetailsServiceImpl, requestFactory, GRANT_TYPE);
        this.userDetailsServiceImpl = userDetailsServiceImpl;
    }

    @Override
    protected ClientUserDetails getUserDetails(Map<String, String> parameters) {
        String phone = parameters.get(PHONE_PARAM);
        String smsCode = parameters.get(CODE_PARAM);
        String key = parameters.get(KEY_PARAM);
        String openId = parameters.get(OPEN_PARAM);
        WxSmsCodeModel wxSmsCodeModel = new WxSmsCodeModel();
        wxSmsCodeModel.setCode(smsCode);
        wxSmsCodeModel.setPhone(phone);
        wxSmsCodeModel.setKey(key);
        wxSmsCodeModel.setOpenId(openId);
        return userDetailsServiceImpl.loadUserByPhoneAndSmsCode(wxSmsCodeModel);
    }
}
